import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'screens/home_screen.dart';
import 'screens/login_screen.dart';
import 'services/admin_service.dart';
import 'services/auth_service.dart';
import 'services/cart_service.dart';
import 'services/order_service.dart';
import 'services/product_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final prefs = await SharedPreferences.getInstance();
  runApp(MyApp(prefs: prefs));
}

class MyApp extends StatelessWidget {
  final SharedPreferences prefs;

  const MyApp({Key? key, required this.prefs}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider<AuthService>(
          create: (_) => AuthService(prefs),
        ),
        ProxyProvider<AuthService, ProductService>(
          update: (_, authService, __) => ProductService(authService),
        ),
        ProxyProvider<AuthService, CartService>(
          update: (_, authService, __) => CartService(authService),
        ),
        ProxyProvider<AuthService, OrderService>(
          update: (_, authService, __) => OrderService(authService),
        ),
        ProxyProvider<AuthService, AdminService>(
          update: (_, authService, __) => AdminService(authService),
        ),
      ],
      child: MaterialApp(
        title: '商城系统',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: const AuthWrapper(),
      ),
    );
  }
}

class AuthWrapper extends StatelessWidget {
  const AuthWrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<AuthService>(
      builder: (context, authService, _) {
        return FutureBuilder<bool>(
          future: authService.loadUser(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Scaffold(
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            }

            if (authService.currentUser != null) {
              return const HomeScreen();
            }

            return const LoginScreen();
          },
        );
      },
    );
  }
}
